<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("分类目录") }}
          <div
            class="tree-setting-btn"
            v-if="lr_hasPageAuth('classifysSetting', 'buttons')"
          >
            <el-tooltip effect="dark" :content="$t('分类管理')" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <el-tree
          class="learun-tree"
          default-expand-all
          :data="dataItemTree_DatasourceType"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            <i class="el-icon-notebook-2"></i>
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入要查询关键字')"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
              :loading="tableLoading"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns :hasAdd="false">
          <el-dropdown
            size="mini"
            @command="handleCommand"
            split-button
            type="primary"
            @click="handleCommand('sql')"
          >
            {{ $t("新增SQL视图") }}
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="table">
                {{ $t("表视图") }}
              </el-dropdown-item>
              <el-dropdown-item command="code">
                {{ $t("JS脚本视图") }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableData"
        :loading="tableLoading"
        row-key="f_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
      >
        <template v-slot:f_Type="scope">
          <el-tag
            v-if="scope.row.f_Type == '1'"
            size="mini"
            type="success"
            >{{ $t("表") }}</el-tag
          >
          <el-tag
            v-else-if="scope.row.f_Type == '2'"
            size="mini"
            type="warning"
            >{{ $t("JS") }}</el-tag
          >
          <el-tag v-else size="mini">{{ $t("SQL") }}</el-tag>
        </template>
        <l-table-btns
          :filterBtns="filterBtns"
          :btns="tableBtns"
          @click="lr_handleTableBtnClick"
        ></l-table-btns>
      </l-table>
    </l-panel>

    <!--sql视图-->
    <l-fullscreen-dialog
      :title="formSqlViewTitle"
      :visible.sync="formSqlViewVisible"
      @ok="handleFormSqlViewSave"
      @close="handleFormSqlViewClose"
      @opened="handleFormSqlViewOpened"
    >
      <form-sql-view ref="formSqlView" />
    </l-fullscreen-dialog>

    <!--表视图-->
    <l-fullscreen-dialog
      :title="formTableViewTitle"
      :visible.sync="formTableViewVisible"
      @ok="handleFormTableViewSave"
      @close="handleFormTableViewClose"
      @opened="handleFormTableViewOpened"
    >
      <form-table-view ref="formTableView" />
    </l-fullscreen-dialog>

    <!--脚本视图-->
    <l-fullscreen-dialog
      :title="formCodeViewTitle"
      :visible.sync="formCodeViewVisible"
      @ok="handleFormCodeViewSave"
      @close="handleFormCodeViewClose"
      @opened="handleFormCodeViewOpened"
    >
      <form-code-view ref="formCodeView" />
    </l-fullscreen-dialog>

    <l-drawer
      :title="`${$t('查看数据源数据')}-${name}`"
      :visible.sync="lookVisible"
      :showOk="false"
      :showClose="false"
      :width="800"
      @close="handleCloseLookForm"
      @opened="handleOpenedLookForm"
    >
      <look-form ref="lookForm" :code="code"></look-form>
    </l-drawer>

    <l-drawer
      :title="$t('分类管理')"
      :visible.sync="classifysVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <l-dataitem-index classifyCode="datasourceType"></l-dataitem-index>
    </l-drawer>
  </l-layout>
</template>

<script>
const api = window.$api.data.dbsource;
import LookForm from "./lookForm.vue";
import FormSqlView from "./formSqlView";
import FormTableView from "./formTableView";
import FormCodeView from "./formCodeView";
export default {
  components: {
    LookForm,
    FormSqlView,
    FormTableView,
    FormCodeView,
  },
  data() {
    return {
      lr_isPage: true,

      classifysVisible: false,
      category: "",
      //查询
      searchWord: "",

      tableLoading: false,
      columns: [
        { label: "类型", prop: "f_Type", width: "60",align:'center' },
        { label: "编码", prop: "f_Code", minWidth: "160" },
        { label: "名称", prop: "f_Name", minWidth: "150" },
        {
          label: "分类",
          prop: "f_Category",
          width: "120",
          dataType: "dataItem",
          dataCode: "datasourceType",
        },
        { label: "创建用户", prop: "f_CreateUserName", width: "100" },
        {
          label: "最后更新",
          prop: "f_ModifyDate",
          width: "160",
          dataType: "datetime",
        },
      ],
      tableBtns: [
        { prop: "LookData", label: "查看",width:40 },
        { prop: "Edit", label: "编辑",width:40 },
        { prop: "Delete", label: "删除",width:40 },
      ],
      tableData: [],
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,

      formVisible: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      lookVisible: false,
      code: "",
      name: "",

      // sql视图
      formSqlViewTitle: "",
      formSqlViewVisible: false,

      // 表视图
      formTableViewTitle: "",
      formTableViewVisible: false,

      // 脚本视图
      formCodeViewTitle: "",
      formCodeViewVisible: false,
    };
  },

  computed: {
    dataItemTree_DatasourceType() {
      return this.lr_dataItemTree(this.lr_dataItem["datasourceType"]);
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    handleSettingClick() {
      this.classifysVisible = true;
    },
    handleNodeClick(data) {
      this.category = data.value;
      this.hanleSearch();
    },

    init() {
      this.lr_loadDataItem("datasourceType");
      this.loadTableData();
    },
    async loadTableData(isNotFirst) {
      if (!isNotFirst) {
        this.tableCurrentPage = 1;
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_ModifyDate DESC",
        keyword: this.searchWord,
        category: this.category,
      };
      const res = await this.$awaitWraper(api.getPage(queryData));
      if (res) {
        this.tableData = res.rows;
        this.tableTotal = res.records;
        this.tableLoading = false;
      }
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTableData(true);
    },

    hanleSearch() {
      this.loadTableData();
    },

    handleCommand(type) {
      this.formEdit = false;
      this.formEditRow = null;
      switch (type) {
        case "sql":
          this.openForm(0);
          break;
        case "table":
          this.openForm(1);
          break;
        case "code":
          this.openForm(2);
          break;
      }
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.openForm(row.f_Type, row.f_Name);
    },

    handleDelete($index, row) {
      this.$confirm(
        this.$t("此操作将永久删除该数据, 是否继续?"),
        this.$t("提示"),
        {
          confirmButtonText: this.$t("确定"),
          cancelButtonText: this.$t("取消"),
          type: "warning",
        }
      )
        .then(() => {
          api.remove(row.f_Id).then(() => {
            this.$message({
              type: "success",
              message: this.$t("删除成功!"),
            });
            this.init();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: this.$t("已取消删除"),
          });
        });
    },

    // SQL视图
    async handleFormSqlViewSave(showLoading, hideLoading) {
      showLoading();
      const valid = await this.$refs.formSqlView.validateForm();
      if (valid) {
        const formData = this.$refs.formSqlView.getForm();
        await this.saveForm(formData);
        this.formSqlViewVisible = false;
      }
      hideLoading();
    },
    handleFormSqlViewClose() {
      this.$refs.formSqlView.resetForm();
    },
    async handleFormSqlViewOpened(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.loadForm("formSqlView");
        hideLoading();
      }
    },

    // 表格视图
    async handleFormTableViewSave(showLoading, hideLoading) {
      showLoading();
      const valid = await this.$refs.formTableView.validateForm();
      if (valid) {
        const formData = this.$refs.formTableView.getForm();
        await this.saveForm(formData);
        this.formTableViewVisible = false;
      }
      hideLoading();
    },
    handleFormTableViewClose() {
      this.$refs.formTableView.resetForm();
    },
    async handleFormTableViewOpened(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.loadForm("formTableView");
        hideLoading();
      }
    },

    // js脚本视图
    async handleFormCodeViewSave(showLoading, hideLoading) {
      showLoading();
      const valid = await this.$refs.formCodeView.validateForm();
      if (valid) {
        const formData = this.$refs.formCodeView.getForm();
        await this.saveForm(formData);
        this.formCodeViewVisible = false;
      }
      hideLoading();
    },
    handleFormCodeViewClose() {
      this.$refs.formCodeView.resetForm();
    },
    async handleFormCodeViewOpened(showLoading, hideLoading) {
      if (this.formEdit) {
        showLoading("加载数据中...");
        await this.loadForm("formCodeView");
        hideLoading();
      }
    },

    openForm(type, name) {
      switch (type) {
        case 1:
          this.formTableViewTitle = name? `${this.$t("编辑表视图")}(${name})`:this.$t(`新增表视图`);
          this.formTableViewVisible = true;
          break;
        case 2:
          this.formCodeViewTitle = name? `${this.$t("编辑JS脚本视图")}(${name})`:this.$t(`新增JS脚本视图`);
          this.formCodeViewVisible = true;
          break;
        case 3:
          break;
        default:
          this.formSqlViewTitle = name? `${this.$t("编辑SQL视图")}(${name})`:this.$t(`新增SQL视图`);
          this.formSqlViewVisible = true;
          break;
      }
    },
    async saveForm(formData) {
      let res;
      if (this.formEdit) {
        res = await this.$awaitWraper(
          api.update(this.formEditRow.f_Id, formData)
        );
      } else {
        res = await this.$awaitWraper(api.add(formData));
      }
      if (res) {
        this.$message({
          type: "success",
          message: this.$t("保存成功！"),
        });
        this.loadTableData();
      }
    },
    async loadForm(formName) {
      const data = await this.$awaitWraper(api.get(this.formEditRow.f_Code));
      if (data) {
        this.$refs[formName].setForm(data);
      } else {
        this.$message({
          type: "warning",
          message: this.$t("获取编辑数据失败!"),
        });
        this.formVisible = false;
      }
    },
      
    // 数据视图查看
    handleLookData($index, row) {
      this.lookVisible = true;
      this.code = row.f_Code;
      this.name = row.f_Name;
    },
    handleCloseLookForm() {
      this.$refs.lookForm.resetForm();
    },
    async handleOpenedLookForm(showLoading, hideLoading) {
      showLoading("加载数据中...");
      await this.$refs.lookForm.init();
      hideLoading();
    },

    filterBtns(row, btns) {
      return btns;
      /*if (row.f_IsEdit != 0) {
        return btns;
      } else {
        return [{ prop: "LookData", label: "查看" }];
      }*/
    },
  },
};
</script>
